/**
 * 首页
 * Created by 10691 on 17/5/8.
 */
import React, {Component} from 'react';
import {
    StyleSheet,
    View,
    ListView,
    TouchableHighlight,
    AsyncStorage,
    Modal,
    Animated
} from 'react-native';
import {PullList} from 'react-native-pull';

import MainListItem from '../communals/MainListItem.js'
import HttpUtils from '../http/HttpUtils.js';
import CommunalDetail from '../communals/GoodsDetails.js';
import RealmUtil from '../db/RealmUtil.js';
import {renderFooter} from '../communals/MyExports.js';
import {screenWidth} from '../communals/MyExports.js';
import FilterMenu from '../communals/FilterMenu.js';
import HaiTaoMenuData from '../data/HaiTaoMenuData.json';
import {HeaderTitle} from '../communals/Header.js';

/**
 * 临时this
 */
let tempThis;

export default class HaiTao extends Component {

    static navigationOptions = ({navigation}) => ({
        headerTitle: <HeaderTitle title='海淘' isShowAngle={true}
                                  onPress={() => tempThis.showFilterMenuModel()}/>
    });

    constructor() {
        super();
        this.state = {
            dataSource: new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}),
            isShowFilterMenu: false,
        };

        tempThis = this;

        // 绑定操作
        this.loadData = this.loadData.bind(this);
        this.loadMore = this.loadMore.bind(this);
        this.renderRow = this.renderRow.bind(this)
    }

    componentDidMount() {
        this.loadData();
    }

    componentWillUnmount() {
        // 防止内存泄漏
        tempThis = null;
    }

    render() {
        return (
            <View style={HomeStyles.containerStyle}>
                <PullList
                    ref='pullList'
                    removeClippedSubviews={false}
                    onPullRelease={(resolve) => this.loadData(resolve)}
                    dataSource={this.state.dataSource}
                    renderRow={this.renderRow}
                    style={HomeStyles.listViewStyle}
                    onEndReached={this.loadMore}
                    onEndReachedThreshold={60}
                    renderFooter={() => renderFooter()}/>

                <Modal
                    animationType={'none'}
                    transparent={true}
                    visible={this.state.isShowFilterMenu}
                    onRequestClose={() => this.onModalClose()}>

                    <FilterMenu
                        data={HaiTaoMenuData}
                        loadFilteredData={(mall, cate) => this.loadFilteredData(mall, cate)}
                        removeModal={() => this.onModalClose()}
                        myStyle={{marginTop: 45}}/>
                </Modal>
            </View>
        )
    }

    /**
     * 网络请求加载数据
     * @param resolve
     */
    loadData(resolve) {
        let params = {'count': '10', 'country': 'us'};
        HttpUtils.get('https://guangdiu.com/api/getlist.php', params).then((responseData) => {
            // 清空数据
            this.data = [];

            // 拼接数据
            this.data = this.data.concat(responseData.data);
            this.setState({dataSource: this.state.dataSource.cloneWithRows(this.data)});
            if (resolve !== undefined) {
                setTimeout(() => {
                    resolve()
                }, 1000);
            }

            let dataLastID = responseData.data[responseData.data.length - 1].id;
            AsyncStorage.setItem('dataLastID', dataLastID.toString());

            // 清楚本地存储的数据
            RealmUtil.removeAllData('HaiTaoData');

            // 存储数据到本地
            RealmUtil.create('HaiTaoData', responseData.data);
        }).catch((error) => {
            console.log(error);

            // 拿到本地存储的数据,展示出来,如果没有存储,那就显示无数据页面
            this.data = RealmUtil.loadAll('HaiTaoData');
            this.setState({
                dataSource: this.state.dataSource.cloneWithRows(this.data),
            });
        });
    }

    /**
     * 下拉加载更多
     */
    loadMore() {
        // 读取ID
        AsyncStorage.getItem('dataLastID').then((value) => {
            this.loadMoreData(value);
        });
    }

    /**
     * 加载更多数据
     */
    loadMoreData(value) {
        let params = {'count': 10, 'sinceid': value, 'country': 'us'};
        HttpUtils.get('https://guangdiu.com/api/getlist.php', params).then((responseData) => {

            // 拼接数据
            this.data = this.data.concat(responseData.data);
            this.setState({dataSource: this.state.dataSource.cloneWithRows(this.data)});

            let dataLastID = responseData.data[responseData.data.length - 1].id;
            AsyncStorage.setItem('dataLastID', dataLastID.toString());

        }).catch((error) => {
            console.log(error);
        });
    }

    /**
     * 返回每一个Item
     * @param rowData
     * @returns {XML}
     */
    renderRow(rowData) {
        return (
            <TouchableHighlight
                underlayColor={'#13fff0'}
                onPress={() => {
                    this.props.navigation.navigate('CommunalDetail', {ID: rowData.id});
                }}>
                <View>
                    <MainListItem
                        image={rowData.image}
                        title={rowData.title}
                        mall={rowData.mall}
                        pubTime={rowData.pubtime}
                        fromSite={rowData.fromsite}/>
                </View>
            </TouchableHighlight>
        );
    }

    /**
     * 安卓菜单模态销毁处理
     */
    onModalClose() {
        this.setState({
            isShowFilterMenu: false,
        })
    }

    /**
     * 显示筛选菜单模组
     */
    showFilterMenuModel() {
        this.setState({isShowFilterMenu: true});
    }

    /**
     * 加载筛选数据网络请求
     */
    loadFilteredData(mall, cate) {
        let pullList = this.refs.pullList;
        pullList.scrollTo({y: 0});
        // 执行下拉刷新动画
        pullList.state.pullPan = new Animated.ValueXY({x: 0, y: this.topIndicatorHeight * -1});

        let params = {};
        if (mall === "" && cate === "") {   // 全部
            this.loadData(undefined);
            return;
        }

        if (mall === "") {  // cate 有值
            params = {
                "cate": cate,
                "country": "us"
            };
        } else {
            params = {
                "mall": mall,
                "country": "us"
            };
        }

        HttpUtils.get('https://guangdiu.com/api/getlist.php', params)
            .then((responseData) => {

                // 重新渲染
                this.setState({
                    dataSource: this.state.dataSource.cloneWithRows(responseData.data),
                    loaded: true,
                });

                // 关闭动画
                setTimeout(() => {
                    pullList.resetDefaultXYHandler();
                }, 1000);

                // 存储数组中最后一个元素的id
                let dataLastID = responseData.data[responseData.data.length - 1].id;
                AsyncStorage.setItem('dataLastID', dataLastID.toString());

            })
            .catch((error) => {

            })
    }

}

const HomeStyles = StyleSheet.create({

    containerStyle: {
        flex: 1,
        alignItems: 'center',
    },

    listViewStyle: {
        width: screenWidth,
    },
});
